package com.inspur.cloud.service.dataspace;

import com.inspur.cloud.entity.dataspace.HbaseResourceEntity;
import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.entity.dataspace.UserResourceRelationEntity;
import com.inspur.cloud.entity.dataspace.ao.resource.DistributeAO;
import com.inspur.cloud.entity.dataspace.common.OpEntityResult;
import com.inspur.cloud.entity.dataspace.common.PageReqParam;
import com.inspur.cloud.entity.dataspace.common.PageResult;
import com.inspur.cloud.entity.dataspace.dto.ResourceCommonDTO;
import com.inspur.cloud.entity.dataspace.dto.UserResourceRelationDTO;
import com.inspur.cloud.entity.dataspace.vo.HbaseAddVO;
import com.inspur.cloud.entity.dataspace.vo.HbaseReq;
import com.inspur.cloud.entity.dataspace.vo.HbaseVO;
import com.inspur.cloud.enums.PermissionEnum;
import com.inspur.cloud.enums.ResourceTypeEnum;
import com.inspur.cloud.exception.ApiException;
import com.inspur.cloud.exception.HbaseException;
import com.inspur.cloud.security.AuthorizationHelper;
import com.inspur.cloud.util.StringUtil;
import com.inspur.cloud.util.TConstants;
import com.inspur.cloud.util.TimeHelper;
import com.inspur.cloud.util.UtilTenant;
import org.apache.commons.lang.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HbaseManagerService {
    @Autowired
    private HbaseResourceService hbaseResourceService;
    @PersistenceContext
    private EntityManager em;
    @Autowired
    UserService userService;
    @Autowired
    UserResRelationSerivce userResourceRelationSerice;
    @Autowired
    HbaseService hbaseService;
    @Autowired
    RangerService rangerService;
    @Autowired
    UserResourceRelationService userResourceRelationService;
    @Autowired
    AuthService authService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public PageResult<HbaseVO> showForUser(PageReqParam<HbaseReq> hbaseReq) {
        return getList(hbaseReq);
    }

    public PageResult<HbaseVO> showForAdmin(PageReqParam<HbaseReq> hbaseReq) {
        return getList(hbaseReq);
    }


    public PageResult<HbaseVO> getList(PageReqParam<HbaseReq> hbaseReq) {
        Integer level = 0;
        PageResult<HbaseVO> ret = new PageResult<>();
        if (hbaseReq.getReqParam().getResourceId().equals(0)) {
            level = 1;
        } else {
            HbaseResourceEntity hbaseResourceEntity = hbaseResourceService.findHbaseResourceEntityById(hbaseReq.getReqParam().getResourceId());
            if (hbaseResourceEntity == null) {
                ret.setCount(1L);
                ret.setMsg("当前资源ID不存在");
                ret.setCode(-1);
                return ret;
            }
            level = hbaseResourceEntity.getLevel() + 1;
        }
        StringBuilder sql = new StringBuilder("SELECT h.* FROM hbase_resource h ");
        StringBuilder countSql = new StringBuilder("SELECT count(*) from (SELECT count(*) FROM hbase_resource h ");
        StringBuilder condition = new StringBuilder(" WHERE  h.status=1 ");
        if (hbaseReq.getReqParam().getType() == 1) {
            condition.append(" AND h.owner=1 ");
        } else if (hbaseReq.getReqParam().getType() == 2) {
            if (AuthorizationHelper.isAdmin()) {
                condition.append(" AND h.owner !=").append(TConstants.ADMIN_ID);
            } else if (AuthorizationHelper.isTenant()) {
                condition.append(" AND h.owner=").append(AuthorizationHelper.getUser().getId());
            } else {
                //显示上级租户私有资源下创建并分配给用户的资源
                UserEntity parent = userService.findUserById(AuthorizationHelper.getUser().getParentId());
                condition.append(" AND h.owner=").append(parent.getId());
            }
        } else {
            if (AuthorizationHelper.isUser()) {//既不是自己，也不是管理员，也不是自己的上级
                UserEntity parent = userService.findUserById(AuthorizationHelper.getUser().getParentId());
                condition.append(" AND h.owner!=1 AND h.owner!=").append(AuthorizationHelper.getUser().getId());
                if (parent != null) {
                    condition.append(" AND h.owner!=").append(parent.getId());
                }
            } else {
                condition.append(" AND h.owner!=1 AND h.owner!=").append(AuthorizationHelper.getUser().getId());
            }
        }
 /*       if (!StringUtil.isEmpty(hbaseReq.getReqParam().getResourceName())) {
            if (hbaseReq.getReqParam().getResourceId() == 0) {//顶级
                condition.append(" AND h.space_name  like '%").append(hbaseReq.getReqParam().getResourceName()).append("%'");
            } else {
                condition.append(" AND (h.table_name  like '%").append(hbaseReq.getReqParam().getResourceName()).append("%' ")
                        .append(" OR h.column_family_name like '%").append(hbaseReq.getReqParam().getResourceName()).append("%') ");
            }
        }*/


        if (!StringUtil.isEmpty(hbaseReq.getReqParam().getResourceName())) {
            if (level==1) {//顶级
                condition.append(" AND h.space_name  like '%").append(hbaseReq.getReqParam().getResourceName()).append("%'");
            } else if(level==2){
                condition.append(" AND (h.table_name  like '%").append(hbaseReq.getReqParam().getResourceName()).append("%' ")
                        .append(" OR h.column_family_name like '%").append(hbaseReq.getReqParam().getResourceName()).append("%') ");
            }else{
                condition.append(" AND h.column_family_name like '%").append(hbaseReq.getReqParam().getResourceName()).append("%' ");
            }
        }

        condition.append(" AND h.parent_id= ").append(hbaseReq.getReqParam().getResourceId());
        if (!AuthorizationHelper.isAdmin()) {
            Specification<UserResourceRelationEntity> specification = (Specification<UserResourceRelationEntity>) (root, query, cb) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(root.get("userId"), AuthorizationHelper.getUser().getId()));
                list.add(cb.equal(root.get("resourceType"), ResourceTypeEnum.HBASE.name()));
//                if (!StringUtil.isEmpty(hbaseReq.getReqParam().getResourceName())) {//这个搜索有问题
//                    list.add(cb.like(root.get("resourceContent"), "%" + hbaseReq.getReqParam().getResourceName() + "%"));
//                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            };
            List<UserResourceRelationEntity> urList = userResourceRelationSerice.findAll(specification);
            List<Integer> spaceNameList = new ArrayList<>();
            List<Integer> tableNameList = new ArrayList<>();
            List<Integer> columnFamilyNameList = new ArrayList<>();
            //如果用户有一个库，那就找出这个库所拥有的表和列族，反之如果给了它一个表，就要往上找到它的库（用于显示）
            for (UserResourceRelationEntity ur : urList) {
                if (ur.getResourceLevel() == 1) {
                    spaceNameList.add(ur.getResourceId());//其所拥有的库
                    if (level >= 2) {//向下找
                        List<Integer> tableUnder = hbaseResourceService.findIdByParentId(ur.getResourceId());
                        if (tableUnder != null && tableUnder.size() > 0) {
                            tableNameList.addAll(tableUnder);
                            if (level >= 3) {
                                for (Integer tid : tableUnder) {
                                    List<Integer> columnUnder = hbaseResourceService.findIdByParentId(tid);
                                    if (columnUnder != null && columnUnder.size() > 0) {
                                        columnFamilyNameList.addAll(columnUnder);
                                    }
                                }
                            }
                        }
                    }
                } else if (ur.getResourceLevel() == 2) {
                    tableNameList.add(ur.getResourceId());
                    //再向上去根据表ID找库ID
                    HbaseResourceEntity hbase = hbaseResourceService.findHbaseResourceEntityById(ur.getResourceId());
                    if (hbase != null) {
                        spaceNameList.add(hbase.getParentId());
                    }
                    if (level == 3) {
                        List<Integer> columnUnder = hbaseResourceService.findIdByParentId(ur.getResourceId());
                        if (columnUnder != null && columnUnder.size() > 0) {
                            columnFamilyNameList.addAll(columnUnder);
                        }
                    }
                } else {
                    columnFamilyNameList.add(ur.getResourceId());//加入列族
                    HbaseResourceEntity columnFamily = hbaseResourceService.findHbaseResourceEntityById(ur.getResourceId());
                    if (columnFamily != null) {
                        tableNameList.add(columnFamily.getParentId());//向上找表
                        HbaseResourceEntity table = hbaseResourceService.findHbaseResourceEntityById(columnFamily.getParentId());
                        if (table != null) {//向上找库
                            spaceNameList.add(table.getParentId());
                        }
                    }
                }
            }
            String ids;
            if (level == 1) {
                ids = StringUtil.concatIntListDistinct(spaceNameList, ",");
            } else if (level == 2) {
                ids = StringUtil.concatIntListDistinct(tableNameList, ",");
            } else {
                ids = StringUtil.concatIntListDistinct(columnFamilyNameList, ",");
            }
            if (!StringUtil.isEmpty(ids)) {
                condition.append(" AND h.id in ( ").append(ids).append(" )");
            } else {
                ret.setCount(0L);
                ret.setMsg("查询结果为空");
                ret.setCode(1);
                return ret;
            }
        }
        condition.append("  group by h.id ");
        countSql.append(condition).append(" ) aa");
        sql.append(condition).append("  ORDER BY h.upd_date  DESC limit :limit ,:offset ");
        Query countQuery = em.createNativeQuery(countSql.toString());
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Integer limit = (hbaseReq.getPageIndex() - 1) * hbaseReq.getPageSize();
        Query listQuery = em.createNativeQuery(sql.toString());
        listQuery.setParameter("limit", limit);
        listQuery.setParameter("offset", hbaseReq.getPageSize());
        listQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> result = listQuery.getResultList();
        List<HbaseVO> voList = new ArrayList<>();
        //获取父资源的权限
        Integer resourceId = hbaseReq.getReqParam().getResourceId();
        UserResourceRelationEntity parentUserRelation = null;
        if (resourceId != 0) {
            parentUserRelation = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(resourceId, AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());
            HbaseResourceEntity hbaseResourceEntity = hbaseResourceService.findHbaseResourceEntityById(resourceId); //父资源
            while (parentUserRelation == null) {//如果父资源权限找不到
                hbaseResourceEntity = hbaseResourceService.findHbaseResourceEntityById(hbaseResourceEntity.getParentId());//找爷爷
                if (hbaseResourceEntity == null) {
                    break;
                }
                parentUserRelation = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(hbaseResourceEntity.getId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());//找爷爷的权限
            }
        }
        for (Map map : result) {
            HbaseVO vo = new HbaseVO();
            vo.setSpaceName(map.get("space_name") != null ? map.get("space_name").toString() : "");
            vo.setTableName(map.get("table_name") != null ? map.get("table_name").toString() : "");
            vo.setColumnFamilyName(map.get("column_family_name") != null ? map.get("column_family_name").toString() : "");
            vo.setResourceId(Integer.valueOf(map.get("id").toString()));
            UserResourceRelationEntity userResourceRelationEntity = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(vo.getResourceId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());
            if (userResourceRelationEntity != null && !StringUtil.isEmpty(userResourceRelationEntity.getAuthor())) {
                vo.setPowerList(userResourceRelationEntity.getAuthor());//待完善
            } else {
                vo.setPowerList(parentUserRelation != null ? parentUserRelation.getAuthor() : "");
            }
            vo.setParentId(map.get("parent_id") != null ? Integer.valueOf(map.get("parent_id").toString()) : 0);
            vo.setLevel(map.get("level") != null ? Integer.valueOf(map.get("level").toString()) : 0);
            UserResourceRelationDTO userResourceRelationDTO = userResourceRelationService.queryUserByResourceIdExceptOwner(vo.getResourceId(), ResourceTypeEnum.HBASE, AuthorizationHelper.getUser().getId());
            vo.setTenantList(userResourceRelationDTO.getTannetList());
            vo.setUserList(userResourceRelationDTO.getUserList());
            if (vo.getLevel() == 2) {
                vo.setColumnFamilyNum(hbaseResourceService.findSonNum(vo.getResourceId()));
            }
            vo.setInsDate(map.get("ins_date") != null ? TimeHelper.StringToDate(map.get("ins_date").toString()) : null);
            vo.setUpdDate(map.get("upd_date") != null ? TimeHelper.StringToDate(map.get("upd_date").toString()) : null);
            UserEntity user = userService.findUserById(map.get("creator") != null ? Integer.valueOf(map.get("creator").toString()) : 0);
            vo.setCreator(user == null ? "" : user.getName());
            voList.add(vo);
        }
        ret.setPageList(voList);
        ret.setCount(count.longValue());
        return ret;
    }

    /**
     * 新建HBASE资源
     * @return
     */
    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> addResource(HbaseAddVO hbaseVO) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        Date now = new Date();
        HbaseResourceEntity hbaseResourceEntity = new HbaseResourceEntity();
        HbaseResourceEntity parent = null;//父级
        //String powerStr = StringUtil.isEmpty(hbaseVO.getPowerList()) ? PermissionEnum.getAllPermissionByType(ResourceTypeEnum.HBASE.getType()) : hbaseVO.getPowerList();
        //新建不需要前端传权限
        String powerStr= PermissionEnum.getAllPermissionByType(ResourceTypeEnum.HBASE.getType());
        if (AuthorizationHelper.isAdmin()) {//管理员
            if (hbaseVO.getParentId()!= 0) {
                return OpEntityResult.fail("管理员仅能创建命名空间");
            }
            HbaseResourceEntity exist = hbaseResourceService.findBySpaceName(hbaseVO.getSpaceName());
            if (exist != null) {
                opEntityResult.setCode(-3);
                opEntityResult.setMsg("要创建的命名空间已存在");
                return opEntityResult;
            }
            hbaseResourceEntity.setSpaceName(hbaseVO.getSpaceName());
            hbaseResourceEntity.setParentId(0);
            hbaseResourceEntity.setLevel(1);
            hbaseResourceEntity.setOwner(1);
            hbaseResourceEntity.setStatus(1);
            hbaseResourceEntity.setInsDate(now);
            hbaseResourceEntity.setUpdDate(now);
            hbaseResourceEntity.setCreator(AuthorizationHelper.getUser().getId());
            hbaseResourceService.save(hbaseResourceEntity);
            hbaseService.createNameSpace(hbaseVO.getSpaceName());
            //ranger 授权
            ResourceCommonDTO resourceCommon = userResourceRelationService.getResourceCommon(hbaseResourceEntity.getId(), ResourceTypeEnum.HBASE.getResourceType());
            userResourceRelationService.addUserRelation(resourceCommon,AuthorizationHelper.getUser(),ResourceTypeEnum.HBASE.getResourceType(),powerStr);
            //管理员逻辑end
        } else {//租户
            if (hbaseVO.getParentId() == 0) {
                return OpEntityResult.fail("非管理员不能创建命名空间");
            }
            //租户的话肯定需要并且有parentId
            parent = hbaseResourceService.findHbaseResourceEntityById(hbaseVO.getParentId());
            if (parent == null) {
                return OpEntityResult.fail("父资源不存在，请核查");
            }
            UserResourceRelationEntity ur = null;
            if (parent.getLevel() == 1) {//建表
                ur = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(parent.getId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());
            } else if (parent.getLevel() == 2) {//列族
                ur = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(parent.getId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());
                if (ur == null) {
                    ur = userResourceRelationSerice.findFirstByResourceIdAndUserIdAndResourceType(parent.getParentId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HBASE.name());
                }
            }
            if (ur != null) {//ur一定存在？
                if (StringUtil.isEmpty(ur.getAuthor()) || !ur.getAuthor().contains("create")) {
                    return OpEntityResult.fail("当前资源下你的权限不足/没有新建权限");
                }
            } else {
                return OpEntityResult.fail("当前资源下你没有权限");
            }

            if (parent.getLevel() == 1) {//父级别是1，那就是建表
                if (StringUtil.isEmpty(hbaseVO.getTableName())) {
                    return OpEntityResult.fail("表名参数不能为空");
                }
                HbaseResourceEntity exist = hbaseResourceService.findByTableNameAndParentId(hbaseVO.getTableName(), hbaseVO.getParentId());
                if (exist != null) {
                    return OpEntityResult.fail("要创建的hbase表资源已存在");
                }
                hbaseResourceEntity.setSpaceName(parent.getSpaceName());
                hbaseResourceEntity.setTableName(hbaseVO.getTableName());
                hbaseResourceEntity.setParentId(parent.getId());
                hbaseResourceEntity.setLevel(2);
            } else if (parent.getLevel() == 2) {//建列族
                if (StringUtil.isEmpty(hbaseVO.getColumnFamilyName())) {
                    return OpEntityResult.fail("列族名参数不能为空");
                }
                HbaseResourceEntity exist = hbaseResourceService.findByColumnFamilyNameAndParentId(hbaseVO.getColumnFamilyName(), hbaseVO.getParentId());
                if (exist != null) {
                    return OpEntityResult.fail("要创建的hbase列族资源已存在");
                }
                hbaseResourceEntity.setSpaceName(parent.getSpaceName());
                hbaseResourceEntity.setTableName(parent.getTableName());
                hbaseResourceEntity.setColumnFamilyName(hbaseVO.getColumnFamilyName());
                hbaseResourceEntity.setParentId(parent.getId());
                hbaseResourceEntity.setLevel(3);
            }//对象组装完毕
            Integer columnFamilyId;
            hbaseResourceEntity.setStatus(TConstants.RES_STATUS_AVAILABLE);
            hbaseResourceEntity.setInsDate(now);
            hbaseResourceEntity.setUpdDate(now);
            hbaseResourceEntity.setCreator(AuthorizationHelper.getUser().getId());

            boolean isPublic = false;
            if (hbaseVO.getType() == 1 || TConstants.ADMIN_ID.equals(parent.getOwner())) {
                isPublic = true;
            }
            if (isPublic) {
                hbaseResourceEntity.setOwner(TConstants.ADMIN_ID);
            } else {
                hbaseResourceEntity.setOwner(parent.getOwner());
            }
            hbaseResourceService.save(hbaseResourceEntity);
            //ranger调用
            if (parent.getLevel() == 1) {//加表
                hbaseService.createTableOnNameSpace(parent.getSpaceName(), hbaseVO.getTableName(), new String[]{TConstants.DEFAULTCOLUMNFAMILY});
                //本地表里插入列族的数据
                columnFamilyId = createColumnFamilyWhenCreateTable(TConstants.DEFAULTCOLUMNFAMILY, hbaseResourceEntity, isPublic);//这里需要优化
                parent.setUpdDate(now);
                hbaseResourceService.save(parent);//建了表，父级别需要更新操作时间
            } else {//加列族
                hbaseService.addColFamilyByTable(parent.getSpaceName(), parent.getTableName(), new String[]{hbaseVO.getColumnFamilyName()});
                parent.setUpdDate(now);
                hbaseResourceService.save(parent);//建了列族，父级别需要更新操作时间
            }
        }//用户角色判断end
         //使用级联权限
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hbase资源创建成功");
        opEntityResult.setData(hbaseResourceEntity.getId());
        return opEntityResult;
    }

    /**
     * @param columnFamily 列族数组
     * @param table        列族的爹，也就是表
     * @return
     */
    protected Integer createColumnFamilyWhenCreateTable(String columnFamily, HbaseResourceEntity table, boolean isPublic) {
        Date now = new Date();
        HbaseResourceEntity hbaseResourceEntity = new HbaseResourceEntity();
        hbaseResourceEntity.setParentId(table.getId());
        hbaseResourceEntity.setColumnFamilyName(columnFamily);
        hbaseResourceEntity.setTableName(table.getTableName());
        hbaseResourceEntity.setSpaceName(table.getSpaceName());
        hbaseResourceEntity.setLevel(3);
        if (isPublic) {
            hbaseResourceEntity.setOwner(TConstants.ADMIN_ID);
        } else {
            hbaseResourceEntity.setOwner(AuthorizationHelper.getUser().getId());
        }
        hbaseResourceEntity.setStatus(TConstants.RES_STATUS_AVAILABLE);
        hbaseResourceEntity.setUpdDate(now);
        hbaseResourceEntity.setInsDate(now);
        hbaseResourceEntity.setCreator(AuthorizationHelper.getUser().getId());
        hbaseResourceService.save(hbaseResourceEntity);
        return hbaseResourceEntity.getId();
    }

    protected void createColumnFamilyInUR(String columnFamily, Integer columnFamilyId, UserEntity userEntity, String powerStr, HbaseResourceEntity table) {
        Date now = new Date();
        UserResourceRelationEntity ur = new UserResourceRelationEntity();
        ur.setResourceId(columnFamilyId);
        ur.setInsDate(now);
        ur.setUpdDate(now);
        ur.setStatus(TConstants.RES_STATUS_AVAILABLE);
        ur.setUserId(userEntity.getId());
        ur.setResourceType(ResourceTypeEnum.HBASE.name());
        ur.setResourceContent(table.getSpaceName() + "|" + table.getTableName() + "|" + columnFamily);
        ur.setAuthor(powerStr);
        ur.setResourceLevel(3);
        userResourceRelationSerice.save(ur);
    }

    /**
     * 分配资源
     * @param hbaseDistributeAO
     * @param disToSelf 是否给自己分配
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> disSpace(DistributeAO hbaseDistributeAO, Boolean disToSelf) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HbaseResourceEntity hbaseResourceEntity = hbaseResourceService.findHbaseResourceEntityById(hbaseDistributeAO.getResourceId());
        if (hbaseResourceEntity == null) {
            return new OpEntityResult<>(-1, "指定的资源不存在", -1);
        }
        Integer result=userResourceRelationService.distribute(hbaseDistributeAO,ResourceTypeEnum.HBASE,false);
        opEntityResult.setCode(1);
        if(UtilTenant.empty(hbaseDistributeAO)) {
            opEntityResult.setMsg("分配已置空");
        }else{
            opEntityResult.setMsg("hbase 资源分配成功");
        }
        opEntityResult.setData(result);
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> share(DistributeAO hbaseDistributeAO) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HbaseResourceEntity hbaseResourceEntity = hbaseResourceService.findHbaseResourceEntityById(hbaseDistributeAO.getResourceId());
        if (hbaseResourceEntity == null) {
            return new OpEntityResult<>(-1, "指定的资源不存在", -1);
        }
        if(hbaseResourceEntity.getLevel()!=null && hbaseResourceEntity.getLevel()<=1){
            return new OpEntityResult<>(-1, "命名空间不允许分享", -1);
        }
        Integer result=userResourceRelationService.distribute(hbaseDistributeAO,ResourceTypeEnum.HBASE,true);
        opEntityResult.setCode(1);
        if(UtilTenant.empty(hbaseDistributeAO)) {
            opEntityResult.setMsg("分享已置空");
        }else{
            opEntityResult.setMsg("hbase 资源分享成功");
        }
        opEntityResult.setData(result);
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> delRes(Integer resourceId, String name, Integer keepData) {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HbaseResourceEntity hbase = hbaseResourceService.findHbaseResourceEntityById(resourceId);
        if (hbase == null) {
            return new OpEntityResult<>(1, "指定的资源已经不存在", -1);
        }
        UserEntity currentUser = AuthorizationHelper.getUser();
        if(!AuthorizationHelper.isAdmin()) {
            String auth = authService.getSourceAuth(resourceId, currentUser.getId(), ResourceTypeEnum.HBASE.name());
            if (StringUtils.isEmpty(auth) || !auth.contains("admin") || !auth.contains("write")) {
                if (!currentUser.getId().equals(hbase.getCreator())) {//如果没有权限，也不是创建者本人
                    throw new ApiException("无权删除该资源");
                }
            }
        }
        if (hbase.getLevel() == 3) {
            Integer sonNum = hbaseResourceService.findSonNum(hbase.getParentId());
            if (sonNum <= 1) {
                return OpEntityResult.fail("至少需要保留一个列族");
            }
        }

        if (hbase.getLevel() == 1) {//删命名空间，清空权限
            if (keepData == 0) {
                if (existNamespace(hbase.getSpaceName())) {
                    hbaseService.deleteNameSpace(hbase.getSpaceName());
                }
            }
            deleteDatabaseInData(hbase,keepData);
        } else if (hbase.getLevel() == 2) {//删表
            if (keepData == 0) {
                try {
                    hbaseService.deleteTable(hbase.getSpaceName(), hbase.getTableName());
                }catch (HbaseException e){
                    logger.error("强制删除：",hbase.getId(),e);
                }
            }
            deleteTableInData(hbase,keepData);
        } else if (hbase.getLevel() == 3) {//删列族
            if (keepData == 0) {//不保留数据
                try {
                    hbaseService.delColFamily(hbase.getSpaceName(), hbase.getTableName(), hbase.getColumnFamilyName());
                }catch (HbaseException e){
                    logger.error("强制删除：",hbase.getId(),e);
                }
                userResourceRelationService.deleteAllUserRelations(resourceId,ResourceTypeEnum.HBASE.name());
                hbaseResourceService.deleteById(resourceId);
            } else {
                userResourceRelationService.deleteAllUserRelations(resourceId,ResourceTypeEnum.HBASE.name());
                hbase.setStatus(0);
                hbaseResourceService.save(hbase);
            }
        }
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hbase资源已删除");
        opEntityResult.setData(1);
        return opEntityResult;
    }

    List<HbaseResourceEntity> findByLevelAndStatus(Integer level, Integer status) {
        return hbaseResourceService.findByLevelAndStatus(level, status);
    }

    List<HbaseResourceEntity> findByLevelAndStatusAndOwner(Integer level, Integer status, Integer owner) {
        return hbaseResourceService.findByLevelAndStatusAndOwner(level, status, owner);
    }

    public boolean existNamespace(String namespace) {
        List<String> namespaceList = hbaseService.getAllSpace();
        if (namespaceList != null && namespaceList.size() > 0) {
            return namespaceList.contains(namespace);
        }
        return false;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public Integer deleteTableInData(HbaseResourceEntity table,Integer keepData){
        Integer up=0;
        List<HbaseResourceEntity> son = hbaseResourceService.findByParentId(table.getId());//根据表找到列族
        if (son != null && son.size() > 0) {//删列族
            for (HbaseResourceEntity column : son) {
                userResourceRelationService.deleteAllUserRelations(column.getId(), ResourceTypeEnum.HBASE.name());//删除列的关系
                up++;
                if(keepData==0) {
                    hbaseResourceService.deleteById(column.getId());
                }else{
                    column.setStatus(0);
                    hbaseResourceService.save(column);
                }
            }
        }
        //删表的权限和数据
        userResourceRelationService.deleteAllUserRelations(table.getId(),ResourceTypeEnum.HBASE.name());
        up+=1;
        if(keepData==0) {
            hbaseResourceService.deleteById(table.getId());
        }else{
            table.setStatus(0);
            hbaseResourceService.save(table);
        }
        return up;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public Integer deleteDatabaseInData(HbaseResourceEntity database,Integer keepData){
        Integer up=0;
        List<HbaseResourceEntity> son = hbaseResourceService.findByParentId(database.getId());//找到表
        if (son == null || son.size() == 0) {
            //没有表，啥都不做
        }else { //处理表
            for (HbaseResourceEntity table : son) {
                up += deleteTableInData(table, keepData);
            }
        }
        //处理数据库自身
        userResourceRelationService.deleteAllUserRelations(database.getId(),ResourceTypeEnum.HBASE.name());
        if(keepData==0) {
            hbaseResourceService.deleteById(database.getId());
        }else{
            database.setStatus(0);
            hbaseResourceService.save(database);
        }
        up++;
        return up;
    }

}
